/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: CommonRequestInterceptor
 * @Package com.rx.core.interceptor
 * @Description: feign 拦截器。统一生成请求序列号
 * @author: 陈锦韬
 * @date: 2020\4\19 0019
 * @version V1.0
 * @Copyright: 2020 陈锦韬  All rights reserved.
 */
package com.rx.core.interceptor;

import com.rx.core.base.RxBaseConstant;
import com.rx.core.bean.RxConfigBean;
import com.rx.core.enm.RX_LOG_MODE;
import com.rx.core.util.EmptyChecker;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author: Administrator
 * @Description: feign 拦截器。统一生成请求序列号
 * @date: 2020\4\19 0019
 */
@Slf4j
public class CommonRequestInterceptor implements RequestInterceptor {
    @Autowired
    RxConfigBean rxConfigBean;

    @Autowired
    Environment environment;
    @Override
    public void apply(RequestTemplate template) {
        Map<String,String> headers = getHeaders(getHttpServletRequest());
        for(String headerName : headers.keySet()){
            log.info("报文头:"+headerName);
            template.header(headerName, getHeaders(getHttpServletRequest()).get(headerName));
        }
        /**
         *  TODO:需要分布式统一生成
         */
        template.header(RxBaseConstant.REQUEST_SN, UUID.randomUUID().toString().replace("-", ""));

        template.header(RxBaseConstant.REQUEST_SYSTEM_NAME,rxConfigBean.getApplicationName());
        template.header(RxBaseConstant.REQUEST_SYSTEM_CODE,rxConfigBean.getApplicationCode());
        template.header(RxBaseConstant.PACKET_TYPE, RxBaseConstant.REQUEST_PACKET);
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            log.error(RX_LOG_MODE.ERROR.getFormat(e.getMessage()));
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        if (EmptyChecker.isEmpty(request)){
            return Collections.emptyMap();
        }

        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
